package com.xrui.hbase.codec.impl;

import com.google.common.base.Preconditions;
import com.moz.kiji.delegation.NamedProvider;
import com.xrui.hbase.RowKeyComponents;
import com.xrui.hbase.codec.RowKeyDecoder;
import com.xrui.hbase.schema.RowKeyComponent;
import com.xrui.hbase.schema.RowKeyEncoding;
import com.xrui.hbase.schema.RowKeyFormat;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class RawBytesRowKeyDecoder implements RowKeyDecoder, NamedProvider {
    public static final String PROVIDER_NAME = "RawBytesRowKeyDecoder";

    @Override
    public RowKeyComponents decode(byte[] bytes, RowKeyFormat format) throws IOException {
        Preconditions.checkArgument(format.getEncoding() == RowKeyEncoding.RAW);
        Preconditions.checkArgument(format.getComponents().size() == 1);
        RowKeyComponent component = format.getComponents().get(0);
        switch (component.getType()) {
            case STRING:
                return RowKeyComponents.fromComponents(Bytes.toString(bytes));
            case LONG:
                return RowKeyComponents.fromComponents(Bytes.toLong(bytes));
            case INTEGER:
                return RowKeyComponents.fromComponents(Bytes.toInt(bytes));
            default:
                throw new RuntimeException("Not supported row key component type: " + component.getType());
        }
    }

    @Override
    public String getName() {
        return PROVIDER_NAME;
    }
}
